package com.ruoyi.net.utils;


import java.util.StringTokenizer;

/**
 * @description:
 * @author: Ly
 * @create: 2025-04-15 13:48
 **/
public class IpUtil
{
    // 将 IP 地址转换为 32 位整数
    private static int ipToInt(String ip) {
        StringTokenizer tokenizer = new StringTokenizer(ip, ".");
        int result = 0;
        for (int i = 0; i < 4; i++) {
            result = (result << 8) | Integer.parseInt(tokenizer.nextToken());
        }
        return result;
    }

    // 根据子网前缀长度生成子网掩码
    private static int generateSubnetMask(int prefixLength) {
        return 0xFFFFFFFF << (32 - prefixLength);
    }

    // 判断两个 IP 地址是否在同一网段
    public static boolean isSameSubnet(String ip1, String ip2, int prefixLength) {
        int ipValue1 = ipToInt(ip1);
        int ipValue2 = ipToInt(ip2);
        int subnetMask = generateSubnetMask(prefixLength);

        int network1 = ipValue1 & subnetMask;
        int network2 = ipValue2 & subnetMask;

        return network1 == network2;
    }

    public static void main(String[] args) {
        String ip1 = "192.168.2.10";
        String ip2 = "192.168.1.20";
        int prefixLength = 24;

        boolean isSame = isSameSubnet(ip1, ip2, prefixLength);
        if (isSame) {
            System.out.println("这两个 IP 地址在同一网段。");
        } else {
            System.out.println("这两个 IP 地址不在同一网段。");
        }
    }
}
